var https = require('https');

let getOpenId = (code, work, res, doc = {}, account = 1) => {
  // 微信中转站  提供用户openId  输入：[code]  输出：微信提供的用户openId
  console.log('post api:getOpenId')

  let appId = 'wx20c87eea3546120a';
  let appSecret = '07528664b5dce209524cb067c85b3492';

  if (account == 2) {
    appId = 'wx644901b1aaa553be';
    appSecret = 'db86390ec9da32ac34bcc1d7db6cf28b';
  }

  var wxUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;

  https.get(wxUrl, function (apiRes) {
    var datas = [];
    apiRes.on('data', function (data) {
      datas.push(data);
    })
    apiRes.on('end', function (data) {
      console.log(11, wxUrl, 11, JSON.parse(datas)["openid"], 11, JSON.parse(datas))
      if(account == 3){
        work(JSON.parse(datas));
      }else{
        work(JSON.parse(datas)["openid"], res, doc)
      }
      
      //res.send({error_no: 1, data: datas + ''})
    })
  }).on('error', function (err) {
    console.log('获取openId,异常' + err);
    getOpenId(code, work, res, doc)
    //res.send({error_no: 0, data: '获取微信用户身份失败'})
  })
}

module.exports = {
  getOpenId: getOpenId
}
